const axios = require('axios')
const webpack = require('webpack')
const MemoryFs = require('memory-fs')
const path = require('path')

const getTemplate = () => new Promise((resolve, reject) => {
  axios.get('http://localhost:3001/public/index.html')
    .then((res) => {
      resolve(res.data)
    }).catch(reject)
})
const serverCinfig = require('../../build/webpack.config.server')
const Module = module.constructor
const mfs = new MemoryFs()
const serverCompiler = webpack(serverCinfig)
const ReactDomServer = require('react-dom/server')
const proxy = require('http-proxy-middleware')



serverCompiler.outputFileSystem = mfs
let serverBundle
serverCompiler.watch({}, (err, status) => {
  if (err) {
    throw err
  }
  status = status.toJson()
  status.errors.forEach(err => console.error(err))
  status.warnings.forEach(warn => console.warn(warn))

  const bundlePath = path.join(
    serverCinfig.output.path,
    serverCinfig.output.filename,
  )

  const bundle = mfs.readFileSync(bundlePath, 'utf8')
  const m = new Module()
  m._compile(bundle, 'server-entry.js')
  serverBundle = m.exports.default
})

module.exports = function (app) {
  app.use('/public', proxy({
    target: 'http://localhost:3001',
  }))
  app.get('*', (req, res) => {
    getTemplate().then((template) => {
      const content = ReactDomServer.renderToString(serverBundle)
      res.send(template.replace('<!-- app -->', content))
    })
  })
}
